<?php

namespace app\tickets\controller;

use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use app\api\controller\Commondevice;
use app\api\controller\Test;
use app\common\controller\Common;
use app\index\controller\Base;
use NativePay;
use QRcode;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;
use WxPayConfig;
use WxPayUnifiedOrder;


class Online extends Base
{


    /**
     * 发票操作(需要执行设备接口)
     * @author zhixuedong
     * @date 2021/1/30/030
     */
    public function invoice(){
        $common = new Common();
        $commonDevice = new Test();
        Db::startTrans();
        try{
            $orderTable = "tickets_order";
            $order_id = $_POST['id'];
            $signcode = $_POST['signcode'];
            $detail = Db::name("tickets_order")->alias("a")->join("tickets_order_detail b","a.id = b.order_id")->field("a.id,b.tickets_id,b.effective_time,b.end_time,b.type,b.degree,b.count,a.invoice_count,a.name,a.IDcard,a.mobile")->where(['a.id'=>$order_id])->find();
            //发卡
            //应发卡
            $count = $detail['count'];
            //已发卡
            $invoice_count = $detail['invoice_count']+1;
            //记录发卡
            Db::name("tickets_order")->where(['id'=>$order_id])->setInc('invoice_count',1);

            //判断是否开启校验库
            $checkout_status = Db::name("tickets_config")->value("checkout_status");
            //判断票的来源
            $tickets_card = "tickets_card";
            $cardWhere['no'] = $signcode;
            $cardDetail = $common->public_select($tickets_card,$cardWhere)->find();
            if($checkout_status==1){
                if(empty($cardDetail)){
                    throw new Exception("非法操作:该票不合法");
                }
            }

            //更新票的信息
            if(!empty($cardDetail)){
                $cardWhere['id'] = $cardDetail['id'];
                $cardWhere['order_id'] = $order_id;
                $cardWhere['effectivetime'] = time();
                $common->handle($tickets_card,$cardWhere);
            }

            $tickets_list = "tickets_list";
            $ticketsDetail = Db::name($tickets_list)->where(['signcode'=>$signcode])->value("id");
            if(!empty($ticketsDetail)){
                throw new Exception("请勿重复出票");
            }
            $listData['order_id'] = $order_id;
            $listData['tickets_id'] = $detail['tickets_id'];
            $listData['effective_time'] = $detail['effective_time'];
            $listData['end_time'] = $detail['end_time'];
            $listData['type'] = $detail['type'];
            $listData['signcode'] = $signcode;
            $listData['status'] = 0;
            $listData['addtime'] = time();
            $listData['degree'] = $detail['degree'];
            $listData['create_data'] = date("Y-m-d");

            $listData['name'] = $detail['name'];
            $listData['mobile'] = $detail['mobile'];
            $listData['IDcard'] = $detail['IDcard'];
            $common->handle($tickets_list,$listData);

            //$this->sms(rand(100000,999999),$detail['mobile']);

            //判断是否今天生效
            //当前时间
            $nowtime = date("Y-m-d");
            if($nowtime>=$detail['effective_time']){
                //像设备下发人员信息
                $personsCreate['employeeNo'] = $signcode;
                if(!empty($detail['IDcard'])){
                    $cardNos = [$detail['IDcard'],$signcode];
                }else{
                    $cardNos = [$signcode];
                }
                $personsCreate['personName'] = empty($detail['name'])?"欢迎光临":$detail['name'];
                $startTime = date("Y-m-d\T00:00:01P",strtotime($detail['effective_time']));
                $endtTime = date("Y-m-d\T23:59:59P",strtotime($detail['end_time']));
                $personsCreate['validBeginTime'] = $startTime;
                $personsCreate['validEndTime'] = $endtTime;
                $cardValue = $commonDevice->cardAdd($personsCreate,$cardNos);

                if($cardValue!==true){
                    throw new Exception("发票失败");
                }
            }


            $ordeLog['order_id'] = $order_id;
            $ordeLog['title'] = "订单出票 操作人:管理员【".Session::get("user_name")."】进行出票操作";
            //插入日志
            $ordeLog['remark'] = "票编码:".$signcode;
            $ordeLog['addtime'] = time();
            $ordeLog['add_id'] = Session::get("id");
            $system_order_log = "tickets_order_log";
            $common->handle($system_order_log,$ordeLog);

            if($invoice_count<$count){
                $black['code'] = 1;
            }else{
                $data['id'] = $order_id;
                $data['invoice_status'] = 2;
                $common->handle($orderTable,$data);
                $black['code'] = 0;
            }
            $black['msg'] = "已出票";
            Db::commit();
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }

    /**
     * 更新支付状态
     * @author zhixuedong
     * @date 2021/1/30/030
     */
    public function updatePay(){
        $common = new Common();
        try{
            $orderTable = "tickets_order";
            $order_id = $_POST['id'];
            $data['id'] = $order_id;
            $data['status'] = 2;
            $data['is_pay'] = 2;
            $common->handle($orderTable,$data);

            $ordeLog['order_id'] = $order_id;
            $ordeLog['title'] = "订单付款 操作人:管理员【".Session::get("user_name")."】进行收款";
            //插入日志
            $ordeLog['remark'] = "收款时间:".date("Y-m-d H:i:s");
            $ordeLog['addtime'] = time();
            $ordeLog['add_id'] = Session::get("id");
            $system_order_log = "tickets_order_log";
            $common->handle($system_order_log,$ordeLog);

            $black['code'] = 0;
            $black['msg'] = "操作成功，等待出票";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    /**
     * 轮询操作(查询订单是否已付款)
     * @author zhixuedong
     * @date 2021/1/26/026
     */
    public function showUnreadNews(){
        $common = new Common();
        try{
            $orderTable = "tickets_order";
            $where['id'] = $_POST['id'];
            $is_pay = $common->public_select($orderTable,$where)->value("is_pay");
            if($is_pay==2){
                $black['code'] = 0;
                $black['msg'] = "已付款";
            }else{
                $black['code'] = 2;
                $black['msg'] = "未付款";
            }

        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    /**
     * 生成二维码
     * @author zhixuedong
     * @date 2021/1/25/025
     */
    public function qrcode(){
        error_reporting(E_ERROR);
        require_once ROOT_PATH.'extend/wxpay/example/phpqrcode/phpqrcode.php';
        $data = urlencode($_GET["data"]);
        $url = urldecode($data);
        QRcode::png($url);
    }


    //生成订单号
    public function generateNo(){
        $common = new Common();
        $current_date = date("Ymd");
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        $where['currentDate'] = $current_date;
        $table = "tickets_order";
        $order_sn = $common->public_select($table,$where)->order("order_sn desc")->value('order_sn');
        if(empty($order_sn)){
            $order_sn = $current_date."00001";
        }else{
            $order_sn = $order_sn+1;
        }
        return $order_sn;
    }


    //发送短信
    public function sms($code,$phone){
        $current_date = date("Y-m-d");
        //记录当天发送的数量
        $detail = Db::name("sms")->where(['phone'=>$phone,'current_date'=>$current_date])->find();
//        if($detail['count']>1){
//            throw new Exception("超出当天可发送的数量");
//        }
        if(empty($detail)){
            $data['phone'] = $phone;
            $data['current_date'] = $current_date;
            $data['count'] = 1;
            Db::name("sms")->insert($data);
        }else{
            Db::name("sms")->where(['phone'=>$phone,'current_date'=>$current_date])->setInc("count",1);
        }

        $common = new \app\api\controller\Common();
        require_once ROOT_PATH."extend/sms/api_sdk//vendor/autoload.php";//引入PHPExcel加载文件
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        //可选-启用https协议
        //$request->setProtocol("https");
        // 必填，设置短信接收号码
        $request->setPhoneNumbers($phone);
        // 必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $request->setSignName("鲸探");
        // 必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $request->setTemplateCode("SMS_190283810");
        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
            "code"=>$code,
        ), JSON_UNESCAPED_UNICODE));
        // 可选，设置流水号
        $request->setOutId("yourOutId");
        // 选填，上行短信扩展码（扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段）
        $request->setSmsUpExtendCode("1234567");
        // 发起访问请求
        $acsResponse = $common->getAcsClient()->getAcsResponse($request);
        return $acsResponse;
    }

    /**
     * 生成订单
     * @author zhixuedong
     * @date 2021/1/25/025
     */
    public function createOrder(){
        $common = new Common();
        Db::startTrans();
        try {
            $rule = [
                ["list", "require", "请选择票种"],
                ["name", "require", "购票人不能为空"],
                ["mobile", "require", "手机号不能为空"],
                ["pay_type", "require", "请选择支付方式"],
            ];
            $validate = new Validate($rule);
            $value = $this->request->post();

            $thisWechat = Session::get("thisWechat");
            $value['uniacid'] = $thisWechat['id'];
            if (!$validate->check($value)) {
                throw new Exception($validate->getError());
            }

            $name = empty($_POST['name'])?'':$_POST['name'];
            $mobile = empty($_POST['mobile'])?'':$_POST['mobile'];
            $IDcard = empty($_POST['IDcard'])?'':$_POST['IDcard'];
            $remark = empty($_POST['remark'])?'':$_POST['remark'];

            if(!empty($mobile)){
                if(!$common->isMobile($mobile)){
                    throw new Exception("手机号码格式有误");
                }
            }
            $count = empty($_POST['count'])?1:$_POST['count'];
            //查询票种库存
            $where['id'] = $_POST['list'];
            $publicTable = "tickets_tickets";
            $newSql = $common->public_select($publicTable,$where);
            $product = $newSql->find();

            if(empty($product)){
                throw new Exception("请选择票种");
            }

            if($product['inventory']<=0){
                throw new Exception("票已售完");
            }

            if($product['type']>1){
                if($count>1){
                    throw new Exception("该票种一次只能购买一张");
                }
                if(!$common->setCard($IDcard)){
                    throw new Exception("身份证号码有误");
                }
            }

//            $crew = [];
//            for ($i=1;$i<=$count;$i++){
//                $crew[$i] = ['name'=>$name,'mobile'=>$mobile,'IDcard'=>$IDcard,'face'=>''];
//            }
//            $crew = json_encode($crew);

            //生成核销码
            $order_sn = $this->generateNo();
            //生成订单
            $thisWechat = Session::get("thisWechat");
            $order['uniacid'] = $thisWechat['id'];
            $order['add_id'] = Session::get("id");
            $order['real_pay'] = $product['price']*$count;
            $order['status'] = 1;
            $order['pay_type'] =$_POST['pay_type'];
            $order['is_pay'] = 1;
            $order['total_amount'] = $product['price']*$count;
            $order['order_sn'] = $order_sn;
            $order['addtime'] = time();
            $order['currentDate'] = date("Ymd",time());
            $order['name'] = $name;
            $order['mobile'] = $mobile;
            $order['IDcard'] = $IDcard;
            $order['remark'] = $remark;
            $order['year'] = date("Y",time());
            $order['month'] = date("m",time());
//            $order['crew'] = $crew;

            $orderTable = "tickets_order";
            if(!empty($_POST['order_id'])){
                //获取票的支付状态
                $is_pay = $common->public_select($orderTable,['id'=>$_POST['order_id']])->value("is_pay");
                if($is_pay==1){
                    $order['id'] = $_POST['order_id'];
                }else{
                    $invoice_status = $common->public_select($orderTable,['id'=>$_POST['order_id']])->value("invoice_status");
                    if($invoice_status==1){
                        $black['code'] = 2;
                        $black['msg'] = "操作成功";
                        return $black;
                    }
                }
            }
            $order_id = $common->handle($orderTable,$order);
            $tickets_order_detail = "tickets_order_detail";
            if(!empty($_POST['order_id'])){
                //查询购票信息
                $order_product_where['order_id'] = $order_id;
                $detailId = $common->public_select($tickets_order_detail,$order_product_where)->value("id");
                $order_product['id'] = $detailId;
            }
            //插入票信息
            $order_product['order_id'] = $order_id;
            $order_product['tickets_id'] = $product['id'];
            $order_product['title'] = $product['title'];
            $order_product['thumb'] = $product['thumb'];
            $order_product['type'] = $product['type'];
            $order_product['validity'] = $product['validity'];
            $order_product['price'] = $product['price'];
            $order_product['time_range'] = $product['time_range'];
            $order_product['address'] = $product['address'];
            $order_product['content'] = $product['content'];
            $order_product['count'] = $count;
            $order_product['effective_time'] = empty($_POST['effective_time'])?date("Y-m-d",time()):$_POST['effective_time'];
            $validity = $product['validity']-1;
            $order_product['end_time'] = date("Y-m-d",strtotime("+".$validity." day",strtotime($order_product['effective_time'])));
            $order_product['degree'] = $product['degree'];
            $common->handle($tickets_order_detail,$order_product);
            //减库存
            //$common->public_select($publicTable,$where)->setDec("inventory",intval($count));
            //生成订单操作流程
            $ordeLog['order_id'] = $order_id;
            if(!empty($_POST['order_id'])){
                $ordeLog['title'] = "订单提交成功 操作人:管理员【".Session::get("user_name")."】提交订单";
                //插入日志
                $log['remark'] = "管理员【".Session::get("user_name")."】更新订单，订单编号【".$order_sn."】,关联id【".$order_id."】" ;
            }else{
                $ordeLog['title'] = "订单更新成功 操作人:管理员【".Session::get("user_name")."】更新订单";
                //插入日志
                $log['remark'] = "管理员【".Session::get("user_name")."】提交订单，订单编号【".$order_sn."】,关联id【".$order_id."】" ;
            }

            $ordeLog['remark'] = "核销码:".$order_sn;
            $ordeLog['addtime'] = time();
            $ordeLog['add_id'] = Session::get("id");
            $system_order_log = "tickets_order_log";
            $common->handle($system_order_log,$ordeLog);
            $common->addLog($log);


            switch ($_POST['pay_type']){
                case "1":
                    //生成小程序二维码
                    $applet = new Applet();
                    //生成二维码
                    $url1 = $applet->getWxcode($order_id);
                    break;
                case "3":
//                    $this->sms($order_sn,$order['mobile']);
//                    现金支付
                    $url1 = 0;
                    //生成购票信息
                    $effective_time = date("Y年m月d日",strtotime($order_product['effective_time']));
                    $html = '';
                    $html .= '<div class="cash_div"><span class="">入园日期:</span><span>'.$effective_time.'</span></div>';
                    $html .= '<div class="cash_div"><span class="">票种:</span><span>'.$order_product['title'].'</span></div>';
                    $html .= '<div class="cash_div"><span class="">数量:</span><span>'.$order_product['count'].'</span></div>';
                    $html .= '<div class="cash_div"><span class="">入园地址:</span><span>'.$order_product['address'].'</span></div>';
                    $html .= '<div class="cash_div"><span class="">购票人:</span><span>'.$name.'</span></div>';
                    $html .= '<div class="cash_div"><span class="">手机号:</span><span>'.$mobile.'</span></div>';
                    if($IDcard!=''){
                        $html .= '<div class="cash_div"><span class="">身份证号:</span><span>'.$IDcard.'</span></div>';
                    }
                    $black['html'] = $html;
                    break;
            }

            $black['pay_type'] = $_POST['pay_type'];
            $black['code'] = 0;
            $black['msg'] = "操作成功";
            $black['order_id'] = $order_id;
            $black['url1'] = $url1;
            $black['real_pay'] = $order['real_pay']."元";

            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }

    /**
     * 在线购票
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/25/025
     */
    public function index(){
        $common = new Common();
        //查询票类型
        $common = new Common();
        $tickets_type = $common->publicAttribute("tickets_type");
        $this->assign("tickets_type",$tickets_type);

        //平台支付方式
        $paytype_table = "paytype";
        $where['status'] = 1;
        $field="id,name,icon";
        $paytype = $common->public_select($paytype_table,$where,$field)->select();
        $this->assign("paytype",$paytype);

        $list = $this->selList($common,1);
        $this->assign("list",$list);

        //获取当天日期
        $newtime = date("Y-m-d");
        $this->assign("newtime",$newtime);

        //查询已付款但为发卡的订单
        $tickets_order = "tickets_order";
        $orderWhere['fans_id'] = 0;
        $orderWhere['is_pay'] = 2;
        $orderWhere['invoice_status'] = 1;
        $order = $common->public_select($tickets_order,$orderWhere)->order("id desc")->find();
        if(!empty($order)){
            //查询购票详情
            $tickets_order_detail = "tickets_order_detail";
            $detailWhere['order_id'] = $order['id'];
            $orderDetail = $common->public_select($tickets_order_detail,$detailWhere)->find();

            $this->assign("order",$order);
            $this->assign("orderDetail",$orderDetail);

            //查询对应的票类型
            $tickets_tickets = "tickets_tickets";
            $ticketsWhere['type'] = $orderDetail['type'];
            $ticketsWhere['status'] = 1;
            $field = "id,title";
            $tickets = $common->public_select($tickets_tickets,$ticketsWhere,$field)->select();
            $this->assign("tickets",$tickets);

            return $this->fetch('update');
        }else{
            return $this->fetch('index');
        }
    }


    public function selList($common,$type){
        //票列表
        $thisWechat = Session::get("thisWechat");
        if(!empty($type)){
            $where['type'] = $type;
        }
        $where['uniacid'] = $thisWechat['id'];
        $where['status'] = 1;
        $publicTable = "tickets_tickets";
        $field="id,title,thumb,type,price,inventory,soldout";
        $newSql = $common->public_select($publicTable,$where,$field);
        $list = $newSql->order("sort desc,id desc")->select();
        return $list;
    }


    /**
     * 票详情
     * @return false|string
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function detailApi(){
        $common = new Common();
        try {
            $where['id'] = $_POST['id'];
            $publicTable = "tickets_tickets";
            $field="id,title,thumb,type,price,inventory,soldout,validity,degree,time_range,address,content";
            $newSql = $common->public_select($publicTable,$where,$field);
            $detail = $newSql->order("sort desc,id desc")->find();
            $tickets_type = $common->publicAttribute("tickets_type");
            $detail['type'] = $tickets_type[$detail['type']];
            $black['code'] = 0;
            $black['data'] = $detail;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    /**
     * 获取列表
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function listsApi(){
        $common = new Common();
        try {
            $type = empty($_POST['type'])?1:$_POST['type'];
            $list = $this->selList($common,$type);
            $black['code'] = 0;
            $black['data'] = $list;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }




}